package main

/// https://systembash.com/a-simple-go-tcp-server-and-tcp-client/
// this go exec file is for test purpose, will act as GPRS model in IFMS


import (
	"bufio"
	"fmt"
	"net"
	// "os"
	"strings"
	"time"
)


var data_category []int8 = []int8{1,3,4,5,6}

var data_body = map[int8]string  { 1: "1,2,3,4,5,6,12345678", 3:"3,4,5,6,7"}

const  sla_msec int64 = 1000  // if deply time reach this porint, then we stop load test.


const msg_interval = 30 //  wait 30 second before send next msg to TCP server 

var dev_ct    int64 =0;     
var exceed_sla_ct int64 = 0;


func main() {
	// var text string
	remoteIp := "120.76.151.52"
	remotePort := "9712"

	remoteAddr := remoteIp + ":" + remotePort
	// loopFlag := true
	// svrEcho := true
fmt.Printf(" Remote Addr: %s \n", remoteAddr)	

	//下行数据帧内容如下：#;<1>;<2>;<3>;;
//	validID := regexp.MustCompile(`^#;.{15};1;[0-9]{4},[01][0-9],[0-3][0-9],[0-2][0-9],[0-5][0-9],[0-5][0-9]`)
	 for  exceed_sla_ct < 10 {
//	 for  exceed_sla_ct < 10 {
	 	fmt.Printf("In For loop,  exceed_sla_ct = %v\n", exceed_sla_ct)

		go dev_instance( remoteAddr  )


	time.Sleep( time.Second  *  5 )
		// fmt.Printf("Press any key to continue... ")
		// reader := bufio.NewReader(os.Stdin)
		// 		_ , _ = reader.ReadString('\n')

	}

	time.Sleep( time.Second  * msg_interval *3 )

}


func dev_instance (p_remoteAddr string  ) {
//  msg_interval : in seconds, will wait between next upload 

//	fmt.Print("Dailing to :", remoteAddr, "......")
	dev_id := dev_ct + 1

	dev_ct ++ 

	fmt.Printf("Dev: %v start instance , total dev ct: %v \n ", dev_id, dev_ct  )


	conn, err := net.Dial("tcp", p_remoteAddr)
	if err != nil {
		fmt.Println("Error while dialing: ", err )
		return 
	}

	var loop_ct int64 = 0 
	var elapsed int64 = 0

	fmt.Println ("\nConnected to : ", conn.RemoteAddr())

	defer conn.Close()

	for elapsed  > sla_msec {  // will exit loop only when respond time > sla_msec
	// for loop_ct < 10 {  // will exit loop only when respond time > sla_msec

		loop_t0 := time.Now()


		text := fmt.Sprintf(`#;LOADTEST_D%v;1;1,2,3,4,5,6,%v;`, dev_id, loop_ct )

		fmt.Printf(" >>>Msg will send to Dev_id : %v: %v \n", dev_id, text )
	
		fmt.Fprintf(conn, text+"\n")

		time.Sleep( 10 * time.Microsecond )

		// in this load test, server will guariteen return 1 and only 1 msg 
	 	message, _ := bufio.NewReader(conn).ReadString('\n')

		fmt.Printf("<<<< Message from server: '%s'\n", strings.TrimSpace(message))

	
 		elapsed = int64( time.Since(loop_t0) ) / 1000 

 		///  returns in nanosecond
 		fmt.Printf(`Dev[%v], loop [%v], elapsed: [%v] ms \n `,  dev_id, loop_ct, elapsed/1000 )

		time.Sleep( time.Second  * msg_interval )
		loop_ct  ++ 

	}

	exceed_sla_ct ++ 

	fmt.Printf("Teh %v th instance reach the maxium elapsed time at dev_id:%v.\n ", exceed_sla_ct, dev_id)
}